package com.wyvoid.forum.web.tag;

import com.wyvoid.forum.domain.UserGroup;
import com.wyvoid.forum.domain.User;
import com.wyvoid.forum.domain.SessionUser;
import com.wyvoid.forum.domain.UserProfile;
import com.wyvoid.forum.service.IUserService;
import com.wyvoid.forum.service.IUserGroupService;
import com.wyvoid.forum.util.ForumUtil;
import com.wyvoid.forum.web.listener.UserCounterListener;
import org.apache.commons.lang.StringUtils;

/**
 * User: cjp
 * Date: 2007-7-7
 * Time: 6:30:49
 */
public class ForumFunctions {
    public static UserGroup getUserGroup(long userId) {
        if(userId<=0){
            return null;
        }
        IUserService userService = (IUserService) ForumUtil.context.getBean("userService");
        IUserGroupService userGroupService = (IUserGroupService) ForumUtil.context.getBean("userGroupService");

        User user = userService.getUser(userId);
        if (user.getAdminId() != 0) {
            return userGroupService.getUserGroup(user.getAdminId());
        } else {
            return userGroupService.getUserGroup(user.getGroupId());
        }
    }

    public static User getUser(long userId){
        if(userId<=0){
            return null;
        }

        IUserService userService = (IUserService) ForumUtil.context.getBean("userService");
        return userService.getUser(userId);
    }

    public static int getUserOnline(long userId){
        if(userId==0){
            return SessionUser.OFFLINE;
        }
        SessionUser sessionUser= UserCounterListener.users.get(userId);
        if(sessionUser==null){
            return SessionUser.OFFLINE;
        }else{
            return sessionUser.getOnline();
        }
    }

    public static void switchOnlineStatus(long userId){
        if(userId==0){
            return;
        }
        SessionUser sessionUser= UserCounterListener.users.get(userId);
        if(sessionUser==null){
            return;
        }
        if(sessionUser.getOnline()==SessionUser.HIDDEN){
           sessionUser.setOnline(SessionUser.ONLINE);
        }else{
            sessionUser.setOnline(SessionUser.HIDDEN);
        }
        UserCounterListener.users.put(userId,sessionUser);
    }

    public static String profilePhoto(long userId){
        if(userId==0){
            return (String) ForumUtil.settings.get("defaultProfilePhoto");
        }
        IUserService userService = (IUserService) ForumUtil.context.getBean("userService");
        User user=userService.getUser(userId);
        if(user!=null&& StringUtils.isNotBlank(user.getPhotoUrl())){
            return user.getPhotoUrl();
        }else{
            return (String) ForumUtil.settings.get("defaultProfilePhoto");
        }
    }
}
